#include "stm32f4xx_hal.h"
#include "debug.h"
#include "usart.h"
#include <string.h>
#include "user_task.h"
#include "user_queue.h"
#include "ble.h"
#include "tim.h"
#include "ctrl.h"
USART2_RECEIVETYPE UsartType2;

void UART_RxIdleCallback2(UART_HandleTypeDef *huart)
{
	if ((__HAL_UART_GET_FLAG(huart,UART_FLAG_IDLE) != RESET)) {
		__HAL_UART_CLEAR_IDLEFLAG(&huart2);
		HAL_UART_DMAStop(&huart2);
		UsartType2.RX_Size = RX_LEN2 - huart2.hdmarx->Instance->NDTR;
		/*数据处理，此处入缓存*/
		osMessageQueuePut(myQueue02Handle, &UsartType2, 0U, 0U);
		/*********************************************************************
		 * 两种情况导致dma失能：1.接收溢出 2.在dma关闭期间，串口接收数据
		 * 清除接收溢出标志位，再开启dma进行接收
		 *********************************************************************/
		__HAL_UART_CLEAR_OREFLAG(&huart2);
		HAL_UART_Receive_DMA(&huart2, UsartType2.RX_pData, RX_LEN2);
	}
}

/*输入信息符*/
char *drive_cmd[] = { "go", "back", "stop", };

void ble_rx_deal(USART2_RECEIVETYPE *data)
{
	char *head = NULL;
	char *tail = NULL;
	char *ptr = NULL;
	head = (char*) &data->RX_pData[0];
	tail = (char*) &data->RX_pData[data->RX_Size - 1];
//	debug_printf("%c\r\n",*head);
//	debug_printf("%c\r\n",*tail);
	if ((*head == '{') && (*tail == '}')) {
		ptr = strstr((char*) data->RX_pData, drive_cmd[0]);
		if (ptr != NULL) {
			pwm_value_set(&htim8, TIM_CHANNEL_2, 0);		//left
			pwm_value_set(&htim8, TIM_CHANNEL_3, 0);		//right
			HAL_UART_Transmit(&huart2, (uint8_t*) data->RX_pData, data->RX_Size,
					0xFFFF);
		}

		ptr = strstr((char*) data->RX_pData, drive_cmd[1]);
		if (ptr != NULL) {
			pwm_value_set(&htim8, TIM_CHANNEL_1, 0);		//left
			pwm_value_set(&htim8, TIM_CHANNEL_4, 0);		//right
			HAL_UART_Transmit(&huart2, (uint8_t*) data->RX_pData, data->RX_Size,
					0xFFFF);

		}
		ptr = strstr((char*) data->RX_pData, drive_cmd[2]);
		if (ptr != NULL) {
			pwm_value_set(&htim8, TIM_CHANNEL_2, 2000);		//left
			pwm_value_set(&htim8, TIM_CHANNEL_3, 2000);		//right
			pwm_value_set(&htim8, TIM_CHANNEL_1, 2000);		//left
			pwm_value_set(&htim8, TIM_CHANNEL_4, 2000);		//right
			HAL_UART_Transmit(&huart2, (uint8_t*) data->RX_pData, data->RX_Size,
					0xFFFF);

		}
	}
}

